#    MythMobile, a Django interface to MythTV for mobile devices
#    Copyright (C) 2011 Andrew Wilkinson (andrewjwilkinson@gmail.com)
#
#     This program is free software; you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation; either version 2 of the License, or
#     (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
#     You should have received a copy of the GNU General Public License along
#     with this program; if not, write to the Free Software Foundation, Inc.,
#     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import re
import subprocess
import sys

enable_aac = re.compile("--enable-(\w*aac\w*)")

# -flags +aic+mv4+trell
IPHONE_ENCODER_FORMAT = """/usr/bin/ffmpeg -i %%s %s -async 1 -ab 128k -ac 1 -s 480x360 -vcodec libx264 -vpre fast -vpre ipod320 -b 200k -bt 240k -f mpegts -loglevel quiet %%s"""

audio = "mp3"
lib_aac_codec_map = { "libfaac": "-acodec aac" }

iphone_encoder = None

def detect_encoder():
    global iphone_encoder

    if audio == "aac":
        try:
            encoders = subprocess.check_output("ffmpeg", stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError, cpe:
            encoders = cpe.output

        m = enable_aac.findall(encoders)

        if len(m) == 0:
            print "ffmpeg appears to be compiled without aac support. Please see the README."
            sys.exit(1)

        aac_code = lib_aac_codec_map[m[0]]
    else:
        acodec = "-acodec libmp3lame"

    iphone_encoder = IPHONE_ENCODER_FORMAT % (acodec, )
